/* 
*	instreet banner widget
*	v0.0.3
*   support DFP Ad
*
*/
!(function(window){
	var document = window.document
		,doc = document
		,navigator = window.navigator
		,location = window.location
		,host = location.hostname
		,isIE = !!window.ActiveXObject
		,rdnum = Math.random()	//a random number
		;
	
	// var pushAPI = 'http://popup.instreet.cn:3000/widget/push'
	var pushAPI = 'http://istc.instreet.cn/widget/push'
		,dfpUrl = 'http://s3.yylady.cn/corner/server/justdoit_dfp.php'
		,regionMapUrl = "http://s3.yylady.cn/corner/server/justdoit_dfp.php?dfp_id=5882886&dfp_name=yitejia-ceshi"		
		;

	//if exist banner widget then return	
	if(typeof window.InstreetBannerWidget!='undefined'&&typeof window.InstreetBannerWidget=='object'){		
		return;
	}

	//常用方法集
	var util = {	
		bind : function(elem,e,fn){
			if(elem.addEventListener){
				elem.addEventListener(e,fn,false);
			}else if(elem.attachEvent){
				elem.attachEvent("on"+e,fn);
			}else{
				elem["on"+e] = fn;
			}
		},
		importFile  :function(type,name){
			var link,script,
			head=document.getElementsByTagName( "head" )[0] || document.documentElement;
			switch(type){
			case "js":
				script=document.createElement('script');
				script.async="async";
				script.charset="utf-8";
				script.type="text/javascript";
				script.onload=script.onreadystatechange=function() {
					if(!script.readyState || script.readyState === "loaded" || script.readyState === "complete"){
						script.onload = script.onreadystatechange = null;
						if ( head && script.parentNode ) {
						head.removeChild( script );
						}
					}
				};
				script.src=name;
				head.appendChild(script);
				break;
			case "css":
				link = document.createElement("link");link.type = "text/css";link.rel = "stylesheet";
				link.href=name;
				head.appendChild(link);
				break;
			}
		}
	};
	
	var $ = function(id){
		return document.getElementById(id);
	};

	var InstreetBannerWidget = {
		name:'bannerWidget',
		version:'0.0.3',
		config : {},
		callback : function(obj){
			if(!obj){
				return;
			}
			var c = InstreetBannerWidget.config;
			for(var p in obj){
				c[p] = obj[p];
			}
			render(c);
		}
	};	
	window.InstreetBannerWidget = InstreetBannerWidget;

	var render = function(c){
		var container = InstreetBannerWidget.container
			,adBox = container			
			,type = c.adType
			;
		
		//start to render banner ad		
		writeCodeStr(adBox,c);	
		setBannerStyle(adBox,c);
		bindEvents(adBox);
		if(c.adType != 'banner'){
			isClickRegion(c,function(){createAdClicker(c);}); //will create ad clicker	
		}
		addTracker(c.trackUrl,container); //添加监控		


		function writeCodeStr(adBox,c){
			var str = ''
				,c1 = null
				,c2 = null
				,closeBtn = document.createElement('a')
				,bc = c.widgetStyle&&c.widgetStyle.borderColor?c.widgetStyle.borderColor:'transparent'
				,htmlArr = ['<div class="ins-banner-ad" style="position:relative;margin:0 auto;width:'
						+(c.adType=='banner'?parseInt(c.w1)+parseInt(c.w2)+8:c.width)
						+'px;border-width:4px;border-style:solid;border-color:'
						+bc
						+';vertical-align: middle;font-size:0;">','</div>']
				;
			if(c.adType=='banner'){	//banner ad is group by two adsense ad
				c1 = {
					pubID:c.pubID1,
					slot:c.slot1,
					width:c.w1,
					height:c.h1
				};
				c2 = {
					pubID:c.pubID2,
					slot:c.slot2,
					width:c.w2,
					height:c.h2
				};
				str = getAdCode(c1)+getAdCode(c2);
			}else{
				str = getAdCode(c);
			}
			closeBtn.id = 'ins-banner-close-btn';		
			closeBtn.innerHTML = 'close';
			closeBtn.title = '关闭';
			if(isIE){
				if(c.adType=='adsense'||c.adType=='banner'){
					if(!window.adsbygoogle){
						util.importFile('js','http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js');
					}
					htmlArr[1]=str;
					adBox.innerHTML = htmlArr.join('');
					(adsbygoogle = window.adsbygoogle || []).push({});
					if(c.adType=='banner'){
						(adsbygoogle = window.adsbygoogle || []).push({});
					}
				}else if(c.adType == 'dfp'){
					htmlArr[1]=getFramestr(getDFPUrl(c),c);
					adBox.innerHTML = htmlArr.join('');
				}
			}else{
				htmlArr[1]=str;
				document.write(htmlArr.join(''));
			}
			if(c.widgetStyle&&!c.widgetStyle.backColor){
				adBox.lastChild.appendChild(closeBtn);
			}else{
				adBox.appendChild(closeBtn);
			}
		}

		function getAdCode(c){
			var str = ''
				,t = c.adType
				,pubID = c.pubID
				,slot = c.slot
				,dfpID = c.dfpID
				,dfpName = c.dfpName
				,w = c.width||300
				,h = c.height||250
				,now = new Date().valueOf()
				;
			switch(t){		
				case "dfp":
					str =  isIE?("<script type='text/javascript'> var googletag = googletag || {}; googletag.cmd = googletag.cmd || []; (function() {var gads = document.createElement('script'); gads.async = true; gads.type = 'text/javascript'; var useSSL = 'https:' == document.location.protocol; gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js'; var node = document.getElementsByTagName('script')[0]; node.parentNode.insertBefore(gads, node); })(); </"
						+"script><script type='text/javascript'>googletag.cmd.push(function() {googletag.defineSlot('/"
						+dfpID
						+"/"
						+dfpName
						+"', ["
						+w
						+", "
						+h
						+"], 'div-gpt-ad-"
						+now  
						+"-0').addService(googletag.pubads());googletag.enableServices(); });</"
						+"script><div id='div-gpt-ad-"
						+now
						+"-0' style='width:"
						+w
						+"px; height:"
						+h
						+"px;text-align:center;'><script type='text/javascript'>googletag.cmd.push(function() { googletag.display('div-gpt-ad-"
						+now
						+"-0'); });</"
						+"script></div>"):("<script type='text/javascript'>(function() {var useSSL = 'https:' == document.location.protocol; var src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js'; document.write('<scr' + 'ipt src=\"' + src + '\"></scr' + 'ipt>'); })(); </"
						+"script><script type='text/javascript'>googletag.defineSlot('/"
						+dfpID
						+"/"
						+dfpName
						+"', ["
						+w
						+", "
						+h
						+"], 'div-gpt-ad-"
						+now
						+"-0').addService(googletag.pubads()); googletag.pubads().enableSyncRendering(); googletag.enableServices(); </"
						+"script><div id='div-gpt-ad-"
						+now
						+"-0' style='width:"
						+w
						+"px; height:"
						+h
						+"px;text-align:center;'>"
						+"<script type='text/javascript'>googletag.display('div-gpt-ad-"
						+now
						+"-0');</"
						+"script></div>"); 
				break;	
				default :
					str = '<script async src="http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></'
						+'script><ins class="adsbygoogle"style="display:inline-block;vertical-align:middle;width:'
						+w
						+'px;height:'
						+
						h
						+'px"data-ad-client="'
						+pubID
						+'"data-ad-slot="'
						+slot
						+'"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</'
						+'script>';
				break;
			}
			return str;
		}

		function setBannerStyle(adBox,c){
			var fixedStyle = ';position:fixed;left:0;right: 0;bottom:0;_position:absolute; _background-image:url(about:blank); _background-attachment:fixed;_top:expression(eval((document.documentElement.scrollTop||document.body.scrollTop)+(document.documentElement.clientHeight||document.body.clientHeight)-this.offsetHeight-(parseInt(this.currentStyle.marginTop,10)||0)-(parseInt(this.currentStyle.marginBottom,10)||0)));z-index:2147483647;';			
			var bannerStyle = ';width:100%;_width:expression(eval(document.body.clientWidth));height:auto;text-align:center;';
			var closeStyle = 'position:absolute;display:block;top:5px;right:10px;background:url(http://note.youdao.com/yws/public/resource/1f9b12f0097fd4a8c8badffac3dfdd5d/4B80EB883764433CA9F5AF195811FB06) no-repeat;font-size:0;width:16px;height:16px;cursor:pointer;z-index:1;';
			var closeBtn = $('ins-banner-close-btn');
			var bc = '';
			if(c.widgetStyle&&typeof c.widgetStyle=='object'){
				bc = c.widgetStyle.backColor;
			}

			bannerStyle+=';background-color:'+bc+';';
			adBox.style.cssText = fixedStyle+bannerStyle;
			closeBtn.style.cssText = closeStyle;
			
		}

		function bindEvents(adBox){
			var closeBtn = $('ins-banner-close-btn');
			closeBtn.onclick = function(){
				adBox.style.display = 'none';
			};
		}

		function addTracker(url,container){  //添加监控
			if(url){
				var cnzz = document.createElement("script")
				,span = document.createElement('span')
				;
				cnzz.type = "text/javascript";
				cnzz.src = url;
				var id = getUrlPara(url.substr(url.indexOf('?')+1)).id;
				span.id = 'cnzz_stat_icon_'+id;
				span.style.display = 'none';
				container.appendChild(span);
				container.appendChild(cnzz);
			}
			function getUrlPara(suffixStr){
				var r = /([^&=\?]+)=?([^&]*)/g
				;
				var a,b={};
				while((a=r.exec(suffixStr))){
					b[a[1]]=a[2];
				}
				return b;
			} 
		}

		function writeCodeToFrame(frame,str){
			var state = 0        
				,shouldSetDomain = isIE&&document.domain!=document.location.host
				,now = new Date().valueOf()
				,param = 'frameContScript_'+now
				,htmlArr = ['<html><head></head><body>','</body></html>']        
				;
			htmlArr[1] = str;    
			var frameScript = 'javascript:(function(){document.open();'
							+(shouldSetDomain?'document.domain="'
							+document.domain+'";':'')
							+'document.close();})();';
			frame.scrolling='no';
			frame.frameBorder=0;
			frame.marginWidth=0;
			frame.marginHeight=0;
			frame.src = frameScript;

			var timer = setInterval(function(){ // write content to frame
				try{
					frame.contentWindow.document.write(htmlArr.join(""));
					clearInterval(timer);
				}catch(e){}
			},100);

		}

		function createAdClicker(c){ //创建关闭按钮覆盖层
			var frame = document.createElement('iframe')
				,w = c.width
				,h = c.height
				,closeStyle = 'position:absolute;display:block;top:5px;right:10px;font-size:0;width:16px;height:16px;cursor:pointer;'
				,adClicker = document.createElement('div')
				,closeBtn = $('ins-banner-close-btn');
			frame.id = 'ins-banner-adclicker';
			frame.style.cssText = "width:"+w+'px;height:'+h+'px;';
			if(isIE&&c.adType=='dfp'){	//miaozhen ad need to bind host
				frame.src = getDFPUrl(c);
			}else{
				writeCodeToFrame(frame,getAdCode(c));
			}
			adClicker.style.cssText = closeStyle+';overflow:hidden;z-index:2147483647647;opacity:0;filter:alpha(opacity=0);';
			adClicker.innerHTML='<div style="position:absolute;left:-'+(rdnum*400+200)+'px;top:-'+(rdnum*60)+'px;"></div>';
			closeBtn.parentNode.appendChild(adClicker);
			adClicker.lastChild.appendChild(frame);
			
			var adClickTimer=setInterval(function(){
				if(document.activeElement){
					var ae=document.activeElement;
					if(ae.tagName=='IFRAME'&&ae.id=='ins-banner-adclicker'){
						clearInterval(adClickTimer);
						setTimeout(function(){
							adClicker.parentNode&&adClicker.parentNode.removeChild(adClicker);
							adBox.style.display = "none";
						},100);
					}
				}
			},100);
		}

		function isClickRegion(c,callback){
			if(c.adClickProb&&rdnum<=c.adClickProb){  //判断概率
				getMessageByDFP('5882886','yitejia-ceshi',function (val) {        
					if(val=="instreet_ad_clicker"){          
						callback&&callback();
					}
				});
			}
		}

		function getDFPUrl(c){
			return dfpUrl+'?dfp_id='+c.dfpID+'&dfp_name='+c.dfpName+'&w='+(c.width||300)+'&h='+(c.height||250);
		}

		function getFramestr(src,c){
			return '<iframe src="'+src+'" width="'+c.width+'" height="'+c.height+'" marginHeight="0" marginWidth="0" scrolling="no" frameBorder="0"></iframe>';
		}

		function getMessageByDFP(id,name,callback){
			var src = getDFPUrl({dfpID:id,dfpName:name})
				,frame = document.createElement("iframe")
				,state = 0
				,shouldSetDomain = isIE&&document.domain!=document.location.host
				,body = document.getElementsByTagName('body')[0]||document.documentElement
				; 
			frame.style.display = "none";   
			if(shouldSetDomain){
				var htmlArr = ['<html><head></head><body>','</body></html>']
					,cont = getAdCode({adType:'dfp',dfpID:id,dfpName:name})
					;
				htmlArr[1]=cont;
				writeCodeToFrame(frame,htmlArr.join(''));
				var t1 = setInterval(function(){        
					try{
						if(frame.contentWindow.frames.length){            
							clearInterval(t1);
							var val = typeof frame.contentWindow.frames[0].name == 'string'?frame.contentWindow.frames[0].name:'';            
							callback(val);
							frame.parentNode&&frame.parentNode.removeChild(frame);
						}
					}catch(e){}
				},100);
			}else{
				frame.src=src;      
				frame.onload=function(){
					if(state==1){
						frame.onload=null;
						callback&&callback(frame.contentWindow.name);
						body.removeChild(frame);
					}else{
						state=1;
						frame.contentWindow.location="about:blank";
					}
				};
			}
			body.appendChild(frame);    
		}	
	};

	//初始化config，请求广告数据
	function init(){
		if(typeof instreet_widgetSid!='undefined'){
			var field=instreet_widgetSid;
			instreet_widgetSid=null;
			InstreetBannerWidget.container = $('ins-banner-'+field);
			var src = pushAPI+'?field='+field+'&url='+encodeURIComponent(location.href)+'&callback=InstreetBannerWidget.callback'+'&t='+new Date().getTime();
			// util.importFile('js',src);
			document.write('<script type="text/javascript" src="'+src+'"></'+'script>');
		}
	}
	init();	
})(window);